<template>
  <div id="components-layout-demo-basic" style="width: 1280px; height: 640px; position: relative">
    <div ref="timer" class="timer" v-if="showRankingBoard == false">
      {{ hour + ':' + minute + ':' + second }}
    </div>
    <div style="width: 100%; height: 100%" v-if="showRankingBoard == true">
      <h1>成绩榜</h1>
      <a-table
        :columns="columns"
        :data-source="data"
        bordered
        :pagination="false"
        :scroll="{ y: tableHeight }"
        style="width: 90%; margin: 0 auto"
      >
      </a-table>
    </div>
  </div>
</template>

<script>
import store from '@/store/'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: 'QueryResult',
  data() {
    return {
      showRankingBoard: false,
      tableHeight: 450,
      timer: null,
      matchId: '',
      time: 0,
      form: this.$form.createForm(this, { name: 'coordinated' }),
      hour: '00',
      minute: '00',
      second: '00',
      ms: '000',
      data: [],
      data_origin: [],
      columns: [
        {
          title: '名次',
          dataIndex: 'rank',
          width: '5%',
          align: 'center',
        },
        {
          title: '姓名',
          dataIndex: 'play',
          width: '15%',
          align: 'center',
        },
        {
          title: '号码牌',
          dataIndex: 'playcode',
          width: '14%',
          align: 'center',
        },
        {
          title: '总成绩',
          dataIndex: 'score',
          width: '10%',
          align: 'center',
        },
      ],
    }
  },
  created() {
    this.matchId = this.$route.params.code
    let that = this
    this.timer = window.setInterval(function () {
      that.time = new Date().getTime() - that.$route.params.time
      let temp = that.time
      let hour = 0
      let minute = 0
      let second = 0
      let ms = 0
      hour = Math.floor(temp / 3600000)
      temp -= hour * 3600000
      minute = Math.floor(temp / 60000)
      temp -= minute * 60000
      second = Math.floor(temp / 1000)
      // temp -= second * 1000
      // ms = temp
      if (hour.toString().length > 1) {
        that.hour = hour.toString()
      } else {
        that.hour = '0' + hour.toString()
      }
      if (minute.toString().length > 1) {
        that.minute = minute.toString()
      } else {
        that.minute = '0' + minute.toString()
      }
      if (second.toString().length > 1) {
        that.second = second.toString()
      } else {
        that.second = '0' + second.toString()
      }
      // if (ms.toString().length > 2) {
      //   that.ms = ms.toString()
      // } else if (ms.toString().length > 1) {
      //   that.ms = '0' + ms.toString()
      // } else {
      //   that.ms = '00' + ms.toString()
      // }
      console.log(that.hour, that.minute, that.second)
    }, 1)
  },
  mounted() {
    this.initWebSocket()
    let that = this
    debugger
    //*****************DEMO演示数据*************************
    //ws接入真实数据后删除
    // let demoTimer = window.setTimeout(function () {
    //   window.clearInterval(that.timer)
    //   that.timer = null
    //   let i = 2
    //   that.data_origin = JSON.parse(JSON.stringify(that.data))
    //   that.data = that.data_origin.slice(0, 1)
    //   that.showRankingBoard = true
    //   that.timer = window.setInterval(function () {
    //     that.data = that.data_origin.slice(0, i)
    //     i++
    //     if (i == that.data_origin.length) {
    //       window.clearInterval(that.timer)
    //       that.timer = null
    //     }
    //   }, 3000)
    // }, 5000)
    //*****************************************************
  },
  beforeDestoryed() {
    window.clearInterval(this.timer)
    this.timer = null
  },
  methods: {
    initWebSocket: function () {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var userId = store.getters.userInfo.id
      var url =
        window._CONFIG['domianURL'].replace('https://', 'wss://').replace('http://', 'ws://') + 'matchtime/' + userId
      //console.log(url);
      //update-begin-author:taoyan date:2022-4-22 for:  v2.4.6 的 websocket 服务端，存在性能和安全问题。 #3278
      let token = Vue.ls.get(ACCESS_TOKEN)
      this.websock = new WebSocket(url, [token])
      console.log('url', url)
      console.log('userId', userId)
      console.log('token', token)
      //update-end-author:taoyan date:2022-4-22 for:  v2.4.6 的 websocket 服务端，存在性能和安全问题。 #3278
      this.websock.onopen = this.websocketOnopen
      this.websock.onerror = this.websocketOnerror
      this.websock.onmessage = this.websocketOnmessage
      this.websock.onclose = this.websocketOnclose
    },
    websocketOnopen: function () {
      console.log('Mqtt连接成功')
    },
    websocketOnerror: function (e) {
      console.log('WebSocket连接发生错误，第%s次', this.wsConnectErrorTime)

      this.wsConnectErrorTime = this.wsConnectErrorTime + 1
      if (this.wsConnectErrorTime > 5) {
        console.log('WebSocket连接错误超过5次，就不再重新连了！')
        this.lockReconnect = true
        return
      }

      this.reconnect()
    },
    websocketOnmessage: function (e) {
      let that = this;
      var data = eval('(' + e.data + ')') //解析对象
      console.log('-----接收消息-------', data)
      if (data.success) {
        let rank = that.data.length;
        let rankingItem = {rank: rank + 1}
        for (let key in data.result[key]) {
          if (data.result[key]) {
            rankingItem[key] = data.result[key]
          }
        }
        if (Object.keys(rankingItem).length > 1) {
          that.data.push(rankingItem);
        }
      }
    },
    websocketOnclose: function (e) {
      if (this.websock != null) {
        this.websock.close()
        console.log('connection closed (' + e + ')')
        if (e) {
          console.log('connection closed (' + e.code + ')')
        }
        //this.reconnect();
      }
    },
    websocketSend(text) {
      // 数据发送
      try {
        this.websock.send(text)
      } catch (err) {
        console.log('send failed (' + err.code + ')')
      }
    },
    reconnect() {
      var that = this
      if (that.lockReconnect) return
      that.lockReconnect = true
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        console.info('尝试重连...')
        that.initWebSocket()
        that.lockReconnect = false
      }, 20000)
    },
  },
}
</script>

<style lang="less" scoped>
@font-face {
  font-family: 'RollNum';
  src: url('~@/assets/RollNum.woff') format('woff');
}
#components-layout-demo-basic {
  background-color: #04113d;
}
#components-layout-demo-basic h1 {
  text-align: center;
  font-size: 34px;
  font-weight: bold;
  font-family: Microsoft YaHei;
  color: #fff;
  letter-spacing: 10px;
}
#components-layout-demo-basic h2 {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  font-family: Microsoft YaHei;
  color: #ffb129;
}
#components-layout-demo-basic th td {
  background: rgba(255, 255, 255, 0.3);
}

/deep/ .ant-table-thead > tr > th {
  height: 34px;
  line-height: 34px;
  font-size: 16px;
  font-weight: bold;
  border: 1px solid #007ddb;
  background: rgba(0, 125, 219, 0.3);
  color: #fff;
}
/deep/.ant-table-header {
  background: #031848 !important;
  overflow: hidden !important;
}
/deep/.ant-table-body {
  background: #031848 !important;
}

/deep/ .ant-table-bordered .ant-table-header > table,
.ant-table-bordered .ant-table-body > table,
.ant-table-bordered .ant-table-fixed-left table,
.ant-table-bordered .ant-table-fixed-right table {
  border: 1px solid #007ddb;
  border-bottom: 0;
}
/deep/ .ant-table-bordered .ant-table-tbody > tr > td {
  font-size: 16px;
  font-weight: bold;
  border: 1px solid #007ddb;
  color: #fff;
}

/deep/ .ant-table-bordered .ant-table-body > table {
  border: 1px solid #007ddb;
}

/deep/ ::-webkit-scrollbar {
  width: 0 !important;
  height: 0 !important;
}
/deep/ .ant-table-bordered .ant-table-body > table tbody tr:hover td {
  background: rgba(80, 118, 255, 0.2) !important;
  cursor: pointer;
}
/deep/ .ant-table-bordered .ant-table-body > table tbody tr:nth-child(2n) td {
  background: rgba(80, 118, 255, 0.2) !important;
  cursor: pointer;
}
/deep/ .ant-table-bordered .ant-table-body > table tbody tr:nth-child(1) td {
  background: #ffb129 !important;
  cursor: pointer;
}
/deep/ .ant-table-bordered .ant-table-body > table tbody tr:nth-child(2) td {
  background: #b7b7bc !important;
  cursor: pointer;
}
/deep/ .ant-table-bordered .ant-table-body > table tbody tr:nth-child(3) td {
  background: #cd7f32 !important;
  cursor: pointer;
}
.timer {
  width: 100%;
  height: 100%;
  color: #ffb129;
  font-size: 180px;
  line-height: 640px;
  text-align: center;
  font-family: 'RollNum';
}
</style>